package com.workhours.controller;

import com.workhours.dto.LoginRequest;
import com.workhours.service.AuthService;
import com.workhours.vo.LoginResponse;
import com.workhours.vo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证控制器
 *
 * @author WorkHours
 * @since 2025-09-19
 */
@Tag(name = "认证管理", description = "用户登录认证相关接口")
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    private static final Logger log = LoggerFactory.getLogger(AuthController.class);
    
    @Autowired
    private AuthService authService;
    
    /**
     * 用户登录
     *
     * @param loginRequest 登录请求
     * @return 登录结果
     */
    @Operation(summary = "用户登录", description = "通过口令登录，不存在则自动创建用户")
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            log.info("收到登录请求: {}", loginRequest);
            LoginResponse response = authService.login(loginRequest);
            log.info("登录成功: {}", response);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户登出
     *
     * @return 登出结果
     */
    @Operation(summary = "用户登出", description = "清除当前用户的登录状态和Token")
    @PostMapping("/logout")
    public Result<?> logout() {
        try {
            authService.logout();
            return Result.success("登出成功");
        } catch (Exception e) {
            log.error("登出失败", e);
            return Result.error("登出失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查登录状态
     *
     * @return 登录状态
     */
    @Operation(summary = "检查登录状态", description = "检查当前用户是否已登录")
    @GetMapping("/status")
    public Result<Boolean> checkLoginStatus() {
        boolean isLogin = authService.isLogin();
        return Result.success(isLogin);
    }
}
